package com.atguigu.cloud.common.security;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 安全审计切面
 */
@Slf4j
@Aspect
@Component
public class SecurityAuditAspect {

    @Before("execution(* com.atguigu.cloud.common.https.controller.*.*(..))")
    public void logApiAccess(JoinPoint joinPoint) {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            String clientIp = getClientIpAddress(request);
            String userAgent = request.getHeader("User-Agent");
            String method = request.getMethod();
            String uri = request.getRequestURI();
            
            log.info("API访问 - IP: {}, Method: {}, URI: {}, UserAgent: {}", 
                    clientIp, method, uri, userAgent);
        }
    }

    @AfterThrowing(pointcut = "execution(* com.atguigu.cloud.common.https.controller.*.*(..))", 
                   throwing = "exception")
    public void logApiException(JoinPoint joinPoint, Exception exception) {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            String clientIp = getClientIpAddress(request);
            String uri = request.getRequestURI();
            
            log.error("API异常 - IP: {}, URI: {}, Exception: {}", 
                     clientIp, uri, exception.getMessage(), exception);
        }
    }

    private HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = 
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}